package org.example.medicalstaff.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.example.his.common.api.CommonResponse;
import org.example.medicalstaff.entity.CheckApply;
import org.example.medicalstaff.entity.MedicalDisease;
import org.example.medicalstaff.entity.MedicalRecord;
import org.example.medicalstaff.entity.Register;
import org.example.medicalstaff.mapper.CheckApplyMapper;
import org.example.medicalstaff.mapper.MedicalDiseaseMapper;
import org.example.medicalstaff.mapper.MedicalRecordMapper;
import org.example.medicalstaff.mapper.RegisterMapper;
import org.example.medicalstaff.service.PatientClientService;
import org.example.medicalstaff.utils.DateStringFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Service
public class PatientClientServiceImpl implements PatientClientService {

    @Autowired
    private RegisterMapper registerMapper;
    @Autowired
    private MedicalRecordMapper medicalRecordMapper;
    @Autowired
    private MedicalDiseaseMapper medicalDiseaseMapper;
    @Autowired
    private CheckApplyMapper checkApplyMapper;
    @Autowired
    private Register register;
    @Autowired
    private MedicalRecord medicalRecord;
    @Autowired
    private MedicalDisease medicalDisease;
    @Autowired
    private CheckApply checkApply;

    /**
     * API1 通过查询Register表获取患者信息
     */
    public CommonResponse<List<Register>> getAllPatient(int userID ){
        QueryWrapper<Register> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("UserID",userID);
        List<Register> registerList = registerMapper.selectList(queryWrapper);
        if (registerList != null){
            return CommonResponse.createForSuccess(registerList);
        }else{
            return CommonResponse.createForError("查询失败");
        }
    }

    /**
     * API2 提交患者病历首页信息
     */
    public CommonResponse<String> submit_info(
            String CaseNumber,
            int RegistID,
            String Readme,
            String Present,
            String PresentTreat,
            String History,
            String Allergy,
            String Physique,
            String Proposal,
            String Careful
    ){
        MedicalRecord medicalRecord1 = new MedicalRecord();
        medicalRecord1.setCaseNumber(CaseNumber);
        medicalRecord1.setRegistID(RegistID);
        medicalRecord1.setReadme(Readme);
        medicalRecord1.setPresent(Present);
        medicalRecord1.setPresentTreat(PresentTreat);
        medicalRecord1.setHistory(History);
        medicalRecord1.setAllergy(Allergy);
        medicalRecord1.setPhysique(Physique);
        medicalRecord1.setProposal(Proposal);
        medicalRecord1.setCareful(Careful);
        int result = medicalRecordMapper.insert(medicalRecord1);
        //insert的结果，如果成功返回的是1(可能是这个1是影响的条数)，失败返回的是exception，而不是0。
        if (result == 1){
            List<MedicalRecord> medicalRecordList = medicalRecordMapper.selectList(null);
            int max=0;
            for (int i = 0; i < medicalRecordList.size(); i++) {
                if (medicalRecordList.get(i).getID()>max){
                    max=medicalRecordList.get(i).getID();
                }
            }
            String maxStr = String.valueOf(max);
            return CommonResponse.createForSuccess(maxStr);
        }else{
            return CommonResponse.createForError("提交失败");
        }
    }

    /**
     * API3 重新加载患者病历首页信息
     */
    public CommonResponse<List<MedicalRecord>> refresh(
            String CaseNumber,
            int RegistID
    ){
        QueryWrapper<MedicalRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CaseNumber",CaseNumber);
        queryWrapper.eq("RegistID",RegistID);
        List<MedicalRecord> medicalRecordList = medicalRecordMapper.selectList(queryWrapper);
        if (medicalRecordList.size() != 0){
            return CommonResponse.createForSuccess("刷新成功",medicalRecordList);
        }else{
            return CommonResponse.createForError("刷新失败");
        }
    }

    /**
     * API4 提交初步诊断结果
     */
    public CommonResponse<String> submit_diagnosis(
            int MedicalID,
            int RegistID,
            int DiseaseID,
            int DiagnoseType
    ){
        MedicalDisease medicalDisease = new MedicalDisease();
        medicalDisease.setMedicalID(MedicalID);
        medicalDisease.setDiseaseID(DiseaseID);
        medicalDisease.setRegistID(RegistID);
        medicalDisease.setDiagnoseType(DiagnoseType);
        //设置当前时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = currentDateTime.format(formatter);
        String pattern = "yyyy-MM-dd HH:mm:ss";
        Date date = DateStringFormat.parseDateTimeString(formattedDateTime,pattern);
        medicalDisease.setGetSiskDate(date);
        //设为初诊
        medicalDisease.setDiagnoseCate(1);
        int result = medicalDiseaseMapper.insert(medicalDisease);
        if (result == 1){
            return CommonResponse.createForSuccess("诊断提交成功");
        }else {
            return CommonResponse.createForError("诊断提交失败");
        }
    }

    /**
     * API5 门诊医生查看项目检查结果
     */
    public CommonResponse<CheckApply> look_check_pro(
            int RegistID,
            int MedicalID,
            int ItemID
    ){
        //不需要修改什么，只需要查询就行，获取就行，修改是医技人员做的事情。
        QueryWrapper<CheckApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("RegistID",RegistID);
        queryWrapper.eq("MedicalID",MedicalID);
        queryWrapper.eq("ItemID",ItemID);
        checkApply = checkApplyMapper.selectOne(queryWrapper);
        if (checkApply!=null){
            return CommonResponse.createForSuccess("查看检查结果成功",checkApply);
        }else{
            return CommonResponse.createForError("查看检查结果失败");
        }
    }

    /**
     * API6 提交最终确诊结果
     */
    public CommonResponse<String> final_diagnosis(
            int MedicalID,
            int RegistID,
            String Diagnosis,
            String Handling,
            int DiagnoseCate
    ){
        //首先根据MedicalID修改第三、四个属性
        UpdateWrapper<MedicalRecord> medicalRecordUpdateWrapper = new UpdateWrapper<>();
        medicalRecordUpdateWrapper.set("Diagnosis",Diagnosis)
                .set("Handling",Handling)
                .eq("ID",MedicalID);
        int result = medicalRecordMapper.update(null,medicalRecordUpdateWrapper);
        if (result == 0){
            return CommonResponse.createForError("最终确诊失败");
        }
        //然后根据前两个属性修改后两个属性
        UpdateWrapper<MedicalDisease> medicalDiseaseUpdateWrapper = new UpdateWrapper<>();
        medicalDiseaseUpdateWrapper.set("DiagnoseCate",DiagnoseCate)
                .eq("MedicalID",MedicalID)
                .eq("RegistID",RegistID);
        result = medicalDiseaseMapper.update(null,medicalDiseaseUpdateWrapper);
        if (result == 0){
            return CommonResponse.createForError("最终确诊失败");
        }else{
            return CommonResponse.createForSuccess("最终确诊成功");
        }
    }

    /**
     * API7 结束门诊——诊毕
     */
    public CommonResponse<String> end_service(
            int MedicalID,
            int RegistID
    ){
        UpdateWrapper<MedicalRecord> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("CaseState",3)
                .eq("ID",MedicalID)
                .eq("RegistID",RegistID);
        int result = medicalRecordMapper.update(null,updateWrapper);
        if (result == 0){
            return CommonResponse.createForError("修改状态失败，未查询到");
        }else{
            return CommonResponse.createForSuccess("修改诊毕状态成功");
        }
    }

}
